#!/bin/bash

# project name.
PROJECT_NAME=stevejrong-blog-eureka

# branch name by project.
BRANCH_NAME=develop-1.0.0

# docker registry domain
DOCKER_REGISTRY_DOMAIN=registry.us-west-1.aliyuncs.com
DOCKER_NAMESPACE=stevejrong-blog
DOCKER_REGISTRY_LOGIN_SUCCESS_MSG="Login Succeeded"
DOCKER_REGISTRY_ACCOUNT=1554052208@qq.com

echo ==================================================
echo Script startup for building $PROJECT_NAME
echo ==================================================

echo -e "-------------------- ready go!\n"

# into project git directory.
echo "-------------------- into project git directory"
cd /home/git-repository/$PROJECT_NAME

# build project using gradle command
echo "-------------------- cleanning of compiled classes and files"
gradle clean
echo -e "-------------------- clean success.\n"
sleep 5

echo "-------------------- compiling project"
gradle build
echo -e "-------------------- compile success.\n"
sleep 5

echo "-------------------- creating dockerfile"
gradle task createDockerfile
echo "-------------------- create success.\n"
sleep 5

################# build docker image ##################
# clean old docker images
echo "-------------------- deleting old docker images"
sudo docker rmi $PROJECT_NAME:$BRANCH_NAME
echo "-------------------- delete complete.\n"
sleep 5

# build local docker image
echo "-------------------- building docker image"
sudo docker build -t $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME /home/git-repository/$PROJECT_NAME/build/libs
echo -e "-------------------- build docker image success.\n"
sleep 5

################# push docker image ##################
echo "-------------------- login to Aliyun docker registry"
echo Enter your password:
dockerRegistryLoginResult=`sudo docker login --username=$DOCKER_REGISTRY_ACCOUNT $DOCKER_REGISTRY_DOMAIN`
if [[ $dockerRegistryLoginResult =~ $LOGIN_SUCCESS_MSG ]]
 then
  echo -e "-------------------- login success.\n"
 else
  echo -e "-------------------- login failture, shell exit!\n"
  exit
fi

# find docker image id by docker image name
dockerImageId=`docker images $PROJECT_NAME:$BRANCH_NAME | grep -E -o '[A-Za-z0-9]{12}'`
echo "-------------------- docker image id: " $dockerImageId

echo "-------------------- tagging to local docker image"
sudo docker tag $dockerImageId $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME
echo -e "-------------------- tagged success.\n"

echo "-------------------- pushing local docker image to remote"
sudo docker push $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME
echo -e "-------------------- pushed to remote success.\n"

echo ==================================================
echo build $PROJECT_NAME completed!
echo ==================================================